package com.example.rabbitdemo.simple;

import com.example.rabbitdemo.message.RabbitMQConfig;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class MessageConsumer {
    // 当有消息到达"demo.queue"时，此方法会自动被调用
    @RabbitListener(queues = RabbitMQConfig.QUEUE_NAME)
    public void receiveMessage(String message) {
        System.out.println("接收到的消息: " + message);
        // 在这里编写你的业务处理逻辑
    }

    @RabbitListener(queues = "demo.queue")
    public void receive(String msg, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long tag) throws IOException {
        try {
            System.out.println("<UNK>: " + msg);
            // 业务处理逻辑
            channel.basicAck(tag, false); // 手动确认
        } catch (Exception e) {
            channel.basicNack(tag, false, true); // 处理失败，拒绝消息并可选择重新入队
        }
    }
}